import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_map_demo/address_select.dart';
import 'package:flutter_map_demo/configs/address_select_enums.dart';
import 'package:flutter_map_demo/configs/map_select_config.dart';
import 'package:flutter_map_demo/configs/poi_search_multi_points_config.dart';
import 'package:flutter_map_demo/data_report/poi_search_page_tracker.dart';
import 'package:flutter_map_demo/poi_search/page/poi_search_channel.dart';
import 'package:flutter_map_demo/poi_search/view_model/poi_search_bar_view_model.dart';
import 'package:flutter_map_demo/poi_search/widget/search_bar/input_item.dart';
import 'package:t3_data_service/biz_data_source/common_address/common_address_service.dart';
import 'package:t3_data_service/biz_data_source/map/address/city_pick/city_pick_service.dart';
import 'package:t3_data_service/biz_data_source/map/address/city_pick/model/city_pick_models.dart';
import 'package:t3_data_service/biz_data_source/map/address/city_pick/model/host_model.dart';
import 'package:t3_data_service/biz_data_source/map/address/city_pick/model/open_city_list.dart';
import 'package:t3_data_service/biz_data_source/map/address/poi_search/model/airport_item.dart';
import 'package:t3_data_service/biz_data_source/map/address/poi_search/model/poi_model.dart';
import 'package:t3_data_service/biz_data_source/map/address/poi_search/model/t3_poi_enums.dart';
import 'package:t3_data_service/biz_data_source/map/address/poi_search/model/t3_poi_location.dart';
import 'package:t3_data_service/biz_data_source/map/address/poi_search/model/t3_search_condition.dart';
import 'package:t3_data_service/biz_data_source/map/address/poi_search/model/t3_search_result.dart';
import 'package:t3_data_service/biz_data_source/map/address/poi_search/poi_search_service.dart';
import 'package:t3_data_service/get_data_service.dart';
import 'package:t3_data_service/t3_data_service.dart';
import 'package:t3_foundation/t3_foundation.dart';

import 'package:t3_track/t3_track.dart';
import 'package:uikit/uikit.dart';
import 'dart:io';

import '../../configs/poi_search_base_config.dart';
import '../model/section_builder.dart';
import '../model/section_model.dart';
import '../view_model/poi_search_cell_view_model.dart';
import '../view_model/poi_search_page_view_model.dart';
import '../widget/entry_widget/entry_item.dart';
import '../widget/pop_widget/airport_picker_pop_widget.dart';
import '../widget/pop_widget/enterprise_rule_pois_pop_widget.dart';
import '../widget/pop_widget/entry_change_pop_widget.dart';
import '../widget/pop_widget/share_guide_pop_widget.dart';

class POISearchPageController {
  var dataService = getService<POISearchService>();
  var cityService = getService<CityPickService>();

  OverlayEntry? overlayEntryOfShareGuide;
  
  var pageViewModel = bindVM(POISearchPageViewModel());
  var searchViewModel = bindVM(POISearchBarViewModel());
  var airportViewModel = bindVM(AirportPickerPopViewModel());

  T3SearchCondition? currentCondition;
  T3SearchCondition? lastCondition;
  VoidCallback? toRemoveListener;

  POISearchBaseConfig searchConfig;
  late POISearchStream searchStream;
  late SearchPOITracker tracker;
  List<OpenCity> cityList = [];

  POISearchPageController(POISearchBaseConfig config): searchConfig = config {

    searchConfig = config;
    tracker = SearchPOITracker(searchConfig);

    cityService.getAllCity((p0) {
      cityList = p0;
    });

    searchStream = dataService.getSearchStream();
    ever(searchStream.output, (result){
      if (result != null) {
        lastCondition = result.condition;
        if (result.list.isEmpty) {
          pageViewModel.updateSections([], result.condition.keyword);
        } else {
          List<POIListSection> list = SectionBuilder.fromList(result, searchConfig);
          pageViewModel.updateSections(list, result.condition.keyword);
          tracker.didExposureSearchResult(result.condition, list);
        }
      }
    });
  }

  void dispose() {
    deleteVM(pageViewModel);
    deleteVM(searchViewModel);
    deleteVM(airportViewModel);

    if (toRemoveListener != null) {
      toRemoveListener!();
    }

    searchStream.dispose();
  }

  void reportOnPageShow() {
    var list = pageViewModel.sections.value;
    var page = (searchConfig.pageScene == PageScene.mapSelectSearch) ? 'ChooseViewSpotPageView' : 'ChooseSpotPageView';
    tracker.pageExposure(false, page, list);
  }

  void reportOnForeground() {
    var list = pageViewModel.sections.value;
    var page = (searchConfig.pageScene == PageScene.mapSelectSearch) ? 'ChooseViewSpotPageView' : 'ChooseSpotPageView';
    tracker.pageExposure(true, page, list);
  }

  searchConditionChanged(T3SearchCondition condition) {
    condition.startLocation = searchConfig.originCoor;
    currentCondition = condition;
    T3EnterpriseCondition? eCondition;
    if ((searchConfig.sceneRuleId ?? '').isNotEmpty) {
      eCondition = T3EnterpriseCondition(sceneRuleId: (searchConfig.sceneRuleId ?? ''));
    }
    if (condition.adCode.isNotNullAndEmpty()) {
      //logPOISearchDebug('搜索条件变化：${condition.toString()}');
      searchStream.input.value = (condition, eCondition);
      return;
    }

    //logPOISearchDebug('搜索条件异常：${condition.toString()}');

    if (condition.adCode.isNullOrEmpty()) {
      var result = POISearchChannel.patchCondition(condition.coordinate);
      result.then((value) {
        if (value.item1.isNotNullAndEmpty()) {
          condition.adCode = value.item1;
        }
        if (value.item2.isNotNullAndEmpty() && condition.cityName.isNullOrEmpty()) {
          condition.cityName = value.item2;
        }
        //logPOISearchDebug('搜索条件补偿adCode成功： latlng');
        searchStream.input.value = (condition, eCondition);
      });
    }
  }

  clickSharePOI(BuildContext context, POISearchCellViewModel vm) {
    //logPOISearchDebug('点击分享：${vm.jsonOutput(false).toString()}');
    T3Track.trackEventName('0199008000031', params: {"Terminus" : vm.poi.name});
    // showModalBottomSheet(
    //     backgroundColor: Colors.transparent,
    //     context: context,
    //     builder: (BuildContext context) {
    //       return ShareDestPopWidget(poi: vm, clickCallback: (vm) {
    //         var poi = vm.poi.toJson();
    //         POISearchChannel.sendMsgToChannel('sharePOI', msgData: poi);
    //       },);
    //     });
    //T3Share.sharePoi(context, vm.poi);
  }

  clickCancel() {
    tracker.clickCancel();
    if (searchConfig.pageScene == PageScene.commonAddress || searchConfig.pageScene == PageScene.feedback) {
      BoostNavigator.instance.pop();
      return;
    }
    BoostChannel.instance.sendEventToNative("cancelAddressSelect", {
      "action" : 'searchPageHeaderBar'
    });
  }

  clickHeader(BuildContext context, POIHeaderType type, List<POISearchCellViewModel> list) {
    switch(type) {
      case POIHeaderType.mapSelect:
        //logPOISearchDebug('点击图选按钮');
        T3Track.trackClick('0199.008.000.025');
        gotoMapSelectedPage(
            selectSource: T3MapSelectSource.confusion,
            selectMode: T3MapSelectMode.confusion,
            confusionPoints: list.map((e) => e.poi).toList(),
        );
        break;
    }
  }

  clickFooter(BuildContext context, POIFooterType type, List<POISearchCellViewModel> list) {
      switch(type) {
        case POIFooterType.enterprise:
          //logPOISearchDebug('点击企业用车更多点位');
          showEnterpriseMorePoints(context);
          break;
        case POIFooterType.mapSelect:
          T3Track.trackClick("0199.008.000.022");
          //logPOISearchDebug('点击结合地图搜索');
          gotoMapSelectedPage(
            selectSource: T3MapSelectSource.footerView,
            selectMode: T3MapSelectMode.confusion,
            confusionPoints: list.map((e) => e.poi).toList(),
          );
          break;
      }
  }

  didSelectedPOI(POISearchCellViewModel model) async {
    if (lastCondition != null) {
      tracker.poiDidClick(lastCondition!, model, pageViewModel.sections.value);
    }

    // 如果是终点的场景 并且当前选中的是 终点
    if (isAirportLeavingAndFocusEnd()) {
      //logPOISearchDebug('是送机场景且点击的是终点 不能点击poi');
      return;
    }

    if (!searchConfig.isStartPoint) {
      switch(model.poi.category) {
        case T3POICategory.searchResult:
          model.poi.runtimeParams.destSourceType = DestValuationBubbleSourceType.selectDestPageSearch;
          break;
        case T3POICategory.recommend:
          model.poi.runtimeParams.destSourceType = DestValuationBubbleSourceType.selectDestPageRecommend;
          break;
        case T3POICategory.history:
          model.poi.runtimeParams.destSourceType = DestValuationBubbleSourceType.selectDestPageHistory;
          break;
        default:
          break;
      }
    }

    if (model.poi.category == T3POICategory.enterprise) {
      if (model.poi.city.isNullOrEmpty() && cityList.isNotEmpty) {
        for (var host in cityList) {
          if (host.cityCode == model.poi.cityCode) {
            model.poi.city = host.cityName;
          }
        }
      }
    }

    if (searchConfig.shouldCheckTableSelectedPoi == false) {
      //logPOISearchDebug('选择了终点POI，配置了不需要校验围栏。直接返回：${model.jsonOutput(false).toString()}');
      searchViewModel.updateSelectedModel(model);
      trackPoiDidClickEvent(model);
      return;
    }

    if (searchConfig.pointType != T3POIType.start) {
      if (model.poi.inFenceArea) {
        //logPOISearchDebug('选择了终点POI，围栏。进入图选：${model.jsonOutput(false).toString()}');
        gotoMapSelectedPage(selectSource: T3MapSelectSource.normal, selectMode: T3MapSelectMode.fence, vm: model);
      } else {
        if (model.selectedSubPOIIndex != null) {
          //logPOISearchDebug('选择了终点子POI，不在围栏内，可以返回：${model.jsonOutput(false).toString()}');
          trackPoiDidClickEvent(model);
          searchViewModel.updateSelectedModel(model);
        } else {
          if (searchConfig is POISearchMultiPointsConfig) {
            var multiConfig = searchConfig as POISearchMultiPointsConfig?;
            if (multiConfig != null) {
              if (multiConfig.showConfirmEndPointTag && model.poi.multiPoints) {
                //logPOISearchDebug('选择了终点POI，多下车点。进入图选：${model.jsonOutput(false).toString()}');
                gotoMapSelectedPage(selectSource: T3MapSelectSource.confirm, selectMode: T3MapSelectMode.multiPoint, vm: model);
                return;
              }
            }
          }
          //logPOISearchDebug('选择了终点POI，可以返回：${model.jsonOutput(false).toString()}');
          trackPoiDidClickEvent(model);
          searchViewModel.updateSelectedModel(model);
        }
      }
    } else {
      //logPOISearchDebug('选择了起点POI，直接返回：${model.jsonOutput(false).toString()}');
      trackPoiDidClickEvent(model);
      searchViewModel.updateSelectedModel(model);
    }
  }

  trackPoiDidClickEvent(POISearchCellViewModel model) {
    if (lastCondition != null) {
      var halfwayCount = 0;
      if (!searchConfig.isStartPoint) {
        halfwayCount = searchViewModel.currentPois - 1;
      }
      halfwayCount = min(0, halfwayCount);
      tracker.poiDidFinishSet(lastCondition!, model, halfwayCount);
    }
  }

  deletePOI(POISearchCellViewModel vm, POIListSection section) async {
    //logPOISearchDebug('删除POI');
    var success = await dataService.deletePOI(vm.poi, searchConfig.pointType);
    if (success) {
      List<POIListSection> newSections = [];
      for (var item in pageViewModel.sections.value) {
        if (item.category == section.category) {
          List<POISearchCellViewModel> newList = [];
          for (var e in item.list) {
            if (e.poiName == vm.poiName && e.poiName.isNotEmpty) {
              continue;
            } else {
              newList.add(e);
            }
          }
          if (newList.isNotEmpty) {
            var one = item;
            one.list = newList;
            newSections.add(one);
          }
        } else {
          newSections.add(item);
        }
        pageViewModel.updateSections(newSections, pageViewModel.currentKeyword);
        EasyLoading.showToast('删除成功');
      }
    } else {
      EasyLoading.showToast('删除失败');
    }
  }
}

extension MapSelect on POISearchPageController {
  gotoMapSelectedPage({
    required T3MapSelectSource selectSource,
    required T3MapSelectMode selectMode,
    POISearchCellViewModel? vm,
    List<POIModel>? confusionPoints}) async {

    T3POILocation? location;
    if (currentCondition != null && currentCondition?.cityName != null && currentCondition?.coordinate != null) {
      location = T3POILocation(adCode: currentCondition!.adCode ?? "", cityName: currentCondition!.cityName ?? "", coordinate: currentCondition!.coordinate!);
    } else {
      location = searchConfig.location;
    }
    var config = MapSelectConfig(location: location);
    config.pointType = searchConfig.pointType;
    if (searchConfig.isStartPoint) {
      config.pointType = T3POIType.start;
    } else {
      config.pointType = T3POIType.end;
      if (searchViewModel.isEndPointGetter != null) {
        var isEnd = searchViewModel.isEndPointGetter!();
        if (!isEnd) {
          config.pointType = T3POIType.via;
        }
      }
    }
    config.style = searchConfig.style;
    config.cityScope = searchConfig.cityScope;
    config.allowSelectPoiOutFence = true;
    config.allowMoveOutFence = true;
    config.disappearMode = MapDisappearMode.pop;
    config.keyword = currentCondition?.keyword;
    config.sceneRuleId = searchConfig.sceneRuleId;
    config.mapSelectSource = selectSource;
    config.mode = selectMode;
    config.confusionPoints = confusionPoints;
    String routeName;
    if (searchConfig.pointType != T3POIType.start) {
      routeName = 'mapSelectEndPointsContainer';
      config.spotConfigType = const [MapSpotConfigType.invalidFence, MapSpotConfigType.fence, MapSpotConfigType.personalEnd];
    } else {
      routeName = 'mapSelectStartPointContainer';
      config.spotConfigType = const [MapSpotConfigType.invalidFence, MapSpotConfigType.fence, MapSpotConfigType.personal];
    }
    if (toRemoveListener != null) {
      toRemoveListener!();
    }
    toRemoveListener = BoostChannel.instance.addEventListener('mapSelectPageMsg', (key, arguments) {
      if (key != 'mapSelectPageMsg') {
        return Future.value(null);
      }
      var action = arguments['action'] as String?;
      if (action == null) {
        return Future.value(null);
      }
      if (action == 'poiResult') {
        var data = arguments['data'] as Map?;
        if (data != null) {
          //logPOISearchDebug('图选选择了POI：${data.toString()}');
          var emptyVM = POISearchCellViewModel(POIModel(location: const LatLng(0, 0)), searchConfig);
          emptyVM.updateMapSelectedData(data);
          searchViewModel.updateSelectedModel(emptyVM);
          trackPoiDidClickEvent(emptyVM);
        }
      }
      return Future.value(null);
    });
    var arg = config.toJson();
    if (vm != null) {
      arg['poi'] = vm.poi.toJson();
    }
    //logPOISearchDebug('进入图选页面: ${arg.toString()}');
    BoostNavigator.instance.push(routeName, arguments: arg);
  }
}

extension Enterprise on POISearchPageController {
  showEnterpriseMorePoints(BuildContext context) {
    var sections = pageViewModel.sections.value;
    POIListSection? target;
    for (var item in sections) {
      if (item.category == T3POICategory.enterprise) {
        target = item;
      }
    }
    var list = target?.list ?? [];
    if (list.isEmpty) {
      return;
    }
    showModalBottomSheet(
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        context: context,
        useSafeArea: true,
        builder: (BuildContext context) {
          return EnterpriseRulePOIsPopWidget(
            list: list,
            config: searchConfig,
            didSelectedCallback: (poi) {
              didSelectedPOI(poi);
            },didClickShareButton: (poi) {
              clickSharePOI(context, poi);
          },);
        });
  }

  airportCityChanged(BuildContext context, HostModel city, InputItem inputItem) {
    /// 拉取城市机场信息
    if (city.city.isNullOrEmpty()) {
      return;
    }
    var listFuture = dataService.getCityAirport(city.city!);
    listFuture.then((list) {
      airportViewModel.updateAirport(city.city!, list);
      showModalBottomSheet(
          backgroundColor: Colors.transparent,
          context: context,
          builder: (BuildContext context) {
            return AirportPickerPopWidget(viewModel: airportViewModel, clickCallback: (item) async {
              var adCode = item.adCode;
              var lat = item.latitude;
              var lng = item.longitude;
              if (adCode != null && lat != null && lng != null) {
                var isIn = await cityService.isEndPointInFence(lat, lng, adCode);
                var coordinate = LatLng(double.tryParse(lat) ?? 0, double.tryParse(lng) ?? 0);
                if (isIn) {
                  if (LatLng.isLatLngValid(coordinate)) {
                    airportEnterMap(item, city, coordinate);
                  } else {
                    EasyLoading.showToast('数据解析失败，请重试');
                  }
                } else {
                  var poi = await POISearchChannel.regeoPoint(coordinate);
                  if (poi != null) {
                    var emptyVM = POISearchCellViewModel(POIModel(location: const LatLng(0, 0)), searchConfig);
                    emptyVM.updateMapSelectedData(poi.toJson());
                    searchViewModel.updateSelectedModel(emptyVM);
                  }
                }
              }
            }, clickChangeCity: () {
              var result = BoostNavigator.instance.push('cityPickerPage', arguments: {
                'hintText': "请输入您的目的地城市",
                'cityScope' :CityScope.all.value,
                'autoPop': true,
                'showBack': false,
                'isFromFlutter' : true,
              });
              result.then((value) {
                if (value != null) {
                  var body = value as Map?;
                  if (body != null) {
                    var result = body['result'];
                    if (result == 'data') {
                      var cityData = body['data'];
                      if (cityData != null) {
                        var host = HostModel.fromJson(cityData);
                        //logPOISearchDebug('机场搜索框切换城市：${host.toJson().toString()}');
                        if (host.city.isNotNullAndEmpty()) {
                          var changeList = dataService.getCityAirport(host.city!);
                          changeList.then((value) {
                            airportViewModel.updateAirport(host.city!, value);
                          });
                        }
                      }
                    }
                  }
                }
              });
            });
          });
    });
  }

  airportEnterMap(AirportItem item, HostModel cityInfo, LatLng coordinate) {
    T3POILocation? location = T3POILocation(adCode: item.adCode ?? "", cityName: cityInfo?.city ?? "", coordinate: coordinate);
    var config = MapSelectConfig(location: location);
    config.pointType = T3POIType.end;
    config.style = searchConfig.style;
    config.cityScope = searchConfig.cityScope;
    config.showSearchHeader = false;
    config.allowSelectPoiOutFence = true;
    config.allowMoveOutFence = searchConfig.allowMoveOutFence;
    config.disappearMode = MapDisappearMode.pop;
    String routeName = 'mapSelectAirportPointsContainer';
    config.spotConfigType = const [MapSpotConfigType.fence, MapSpotConfigType.personalEnd];

    var poi = POIModel(location: coordinate);
    poi.address = item.airportName;
    poi.name = item.airportName;
    poi.adCode = cityInfo.adCode ?? "";
    poi.city = cityInfo.city ?? "";
    poi.cityCode = cityInfo.amapCityCode ?? "";
    config.poi = poi;
    
    if (toRemoveListener != null) {
      toRemoveListener!();
    }
    toRemoveListener = BoostChannel.instance.addEventListener('mapSelectPageMsg', (key, arguments) {
      if (key != 'mapSelectPageMsg') {
        return Future.value(null);
      }
      var action = arguments['action'] as String?;
      if (action == null) {
        return Future.value(null);
      }
      if (action == 'poiResult') {
        var data = arguments['data'] as Map?;
        if (data != null) {
          //logPOISearchDebug('图选选择了POI：${data.toString()}');
          var emptyVM = POISearchCellViewModel(POIModel(location: const LatLng(0, 0)), searchConfig);
          emptyVM.updateMapSelectedData(data);
          searchViewModel.updateSelectedModel(emptyVM);
          trackPoiDidClickEvent(emptyVM);
        }
      }
      return Future.value(null);
    });
    var arg = config.toJson();
    //logPOISearchDebug('进入图选页面: ${arg.toString()}');
    BoostNavigator.instance.push(routeName, arguments: arg);
  }
}

extension Share on POISearchPageController {
  showShareGuideCallback(POISearchBaseConfig config, ValueChanged<bool> callback) {
    if (config.pointType == T3POIType.start) {
      return;
    }
    var show = needShowShareGuide();
    show.then((value) {
      callback(value);
    });
  }

  showShareGuide(BuildContext context) async {
    //logPOISearchDebug('展示分享引导弹窗');
    overlayEntryOfShareGuide = OverlayEntry(builder: (incontext) {
      return ShareGuidePopWidget(closeCallback: () {
        removeShareGuide();
      });
    });
    Overlay.of(context).insert(overlayEntryOfShareGuide!);
    KVDB.setBool(Platform.isAndroid ? 'SHARE_ADDRESS_GUIDE' : 'ShareDestGuideController', true);
  }

  removeShareGuide() {
    if (overlayEntryOfShareGuide != null) {
      //logPOISearchDebug('关闭分享引导弹窗');
      overlayEntryOfShareGuide!.remove();
      overlayEntryOfShareGuide = null;
    }
  }

  Future<bool> needShowShareGuide() async {
    var show = await KVDB.getBool(Platform.isAndroid ? 'SHARE_ADDRESS_GUIDE' : 'ShareDestGuideController');
    if (show == true) {
      return false;
    }
    return true;
  }
}

extension HomeAndCompany on POISearchPageController {
  getRemoteCommonUserAddress(BuildContext buildContext, POISearchBaseConfig config) async {
    List<EntryItem> list = [];
    if (config.entryOptions.contains(T3EntryOptions.homeAndCompany)) {
      var result = await CommonAddressService.instance.refresh(isLight: false);
      var home = CommonAddressService.instance.value(AddressSetupType.home);
      var company = CommonAddressService.instance.value(AddressSetupType.company);

      pageViewModel.home = home;
      pageViewModel.company = company;

      /// 家
      EntryItem item1 = EntryItem(
        iconName: "assets/images/poi_common_setup_home.webp",
        title: "家",
        type: EntryItemType.home,
        subtitle: home?.addressTitle ?? "设置家地址",
        detailIconName: "assets/images/poi_common_setup_more.webp",
        showDividerLine: false,
        clicked: () {
          if (isAirportLeavingAndFocusEnd()) {
            //logPOISearchDebug('是送机场景且点击的是终点 不能点击家');
            return;
          }
          clickHome(buildContext);
        },
        clickedDetail: () {
          if (isAirportLeavingAndFocusEnd()) {
            //logPOISearchDebug('是送机场景且点击的是终点 不能点击家的更多');
            return;
          }
          clickHomeMore(buildContext);
        },
      );
      tracker.exposureCommonAddress(home != null, true);
      list.add(item1);

      /// 公司
      EntryItem item2 = EntryItem(
          iconName: "assets/images/poi_common_setup_company.webp",
          title: "公司",
          type: EntryItemType.company,
          subtitle: company?.addressTitle ?? "设置公司地址",
          detailIconName: "assets/images/poi_common_setup_more.webp",
          clicked: () {
            if (isAirportLeavingAndFocusEnd()) {
              //logPOISearchDebug('是送机场景且点击的是终点 不能点击公司');
              return;
            }
            clickCompany(buildContext);
          },
          clickedDetail: () {
            if (isAirportLeavingAndFocusEnd()) {
              //logPOISearchDebug('是送机场景且点击的是终点 不能点击公司更多');
              return;
            }
            clickCompanyMore(buildContext);
          }
      );
      tracker.exposureCommonAddress(company != null, false);
      list.add(item2);
    }

    /// 图选
    if (config.entryOptions.contains(T3EntryOptions.map)) {
      EntryItem item = EntryItem(
        iconName: "assets/images/icon_public_addressinput_map.webp",
        title: "图选",
        type: EntryItemType.map,
        subtitle: "",
        clicked: () {
          T3Track.trackEventName(config.isStartPoint ? '019900600000702' : '019900800000702');
          if (isAirportLeavingAndFocusEnd()) {
            //logPOISearchDebug('是送机场景且点击的是终点 不能点击图选');
            return;
          }
          InputItem? firstRespItem;
          if (searchViewModel.firstRespInputItemGetter != null) {
            firstRespItem = searchViewModel.firstRespInputItemGetter!();
          }
          var selectMode = T3MapSelectMode.common;
          if (firstRespItem?.poi != null) {
            selectMode = T3MapSelectMode.multiPoint;
          }
          gotoMapSelectedPage(
            selectSource: T3MapSelectSource.normal,
            selectMode: selectMode,
            vm: firstRespItem?.poi,
          );
        },
      );

      if (list.isNotEmpty) {
        item.subtitle = "地图选址";
        item.direction = T3EntryItemAxis.vertical;
      } else {
        item.showDividerLine = false;
        item.subtitle = "在地图上选择上车点";
        item.direction = T3EntryItemAxis.horizontal;
        item.detailIconName = "assets/images/icon_rightmore.webp";
      }
      list.add(item);
    }
    pageViewModel.updateEntries(list);
  }

  clickHome(BuildContext buildContext) {
    CommonAddress? item = pageViewModel.home;
    if (item == null) {
      setupCommonAddress(true);
    } else {
      clickCommonAddressPOI(item,true);
    }
  }

  clickCompany(BuildContext buildContext) {
    CommonAddress? item = pageViewModel.company;
    if (item == null) {
      setupCommonAddress(false);
    } else {
      clickCommonAddressPOI(item, false);
    }
  }

  clickHomeMore(BuildContext buildContext) {
    CommonAddress? item = pageViewModel.home;
    if (item == null) {
      setupCommonAddress(true);
    } else {
      clickCommonAddressMore(buildContext, true, item);
    }
  }

  clickCompanyMore(BuildContext buildContext) {
    CommonAddress? item = pageViewModel.company;
    if (item == null) {
      setupCommonAddress(false);
    } else {
      clickCommonAddressMore(buildContext, false, item);
    }
  }

  clickCommonAddressMore(BuildContext buildContext, bool isHome, CommonAddress? item) {
    showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: buildContext,
        builder: (BuildContext context) {
          return EntryChangePopWidget(isHome: isHome, delete: () {
            if (item != null) {
              deleteCommonAddress(item);
            }
          }, change: () {
            setupCommonAddress(isHome);
          },);}
    );
  }

  clickCommonAddressPOI(CommonAddress item, bool isHome) {
    var poi = item.transformToPOI();
    poi.runtimeParams.navPointCheck = true;
    poi.runtimeParams.poiAction = isHome ? PoiAction.home : PoiAction.company;
    poi.runtimeParams.sourceTrack = isHome ? POISourceTrack.home : POISourceTrack.company;
    poi.runtimeParams.destSourceType = isHome ? DestValuationBubbleSourceType.selectDestPageHome : DestValuationBubbleSourceType.selectDestPageCompany;
    var vm = POISearchCellViewModel(poi, searchConfig);
    searchViewModel.updateSelectedModel(vm);
  }

  setupCommonAddress(bool isHome) async {
    T3Track.trackEventName("019919300000102");

    POISearchSinglePointConfig config = POISearchSinglePointConfig(location: searchConfig.location);
    config.originCoor = searchConfig.originCoor;
    config.sceneRuleId = searchConfig.sceneRuleId;
    config.allowMoveOutFence = searchConfig.allowMoveOutFence;
    config.pointType = T3POIType.start;
    config.style = searchConfig.style;
    config.cityScope = CityScope.all;
    config.autoOpenCitySelection = false;
    config.popUntilRoute = searchConfig.popUntilRoute;
    config.entryOptions = [];
    config.showBackButton = false;
    config.shouldCheckTableSelectedPoi = false;
    config.showMapSelectedFooter = false;
    config.showConfusionButton = false;
    config.pageScene = PageScene.commonAddress;
    var result = await openSinglePointPOISearchPage(config, isPresent: false);
    //logPOISearchDebug('设置家和公司数据：${result.toString()}');
    if (result != null && result is Map) {
      var model = result['data'] as List<Map>?;
      if (model != null && model.isNotEmpty) {
        var poi = POIModel.fromJson(model.safeAccess(0));
        var location = poi.location;
        var enterLocation = poi.enterLocation;
        var name = poi.name;
        var sub = poi.subPOIs.safeAccess(0);
        var poiId = poi.poiId;
        if (sub != null) {
          location = sub.location;
          enterLocation = sub.enterLocation;
          name = sub.name;
          poiId = sub.poiId;
        }
        //logPOISearchDebug('设置家和公司数据2：name=$name, lat=${location.lat}, lng=${location.lng}');
        if (poi.location.lat != 0 && poi.location.lng != 0) {
          //logPOISearchDebug('设置家和公司发起请求');
          var result = CommonAddressService.instance.updateCommonAddress(
              isHome ? AddressSetupType.home : AddressSetupType.company,
            poiId: poiId,
            location: location,
            enternLocation: enterLocation,
            addressTitle: name,
            city: poi.city,
            adCode: poi.adCode,
            district: poi.district,
            address: poi.address,
          );
          result.then((value) async {
            //logPOISearchDebug('设置家和公司请求结果：${value}');
            if (value) {
              EasyLoading.showToast('修改成功');

              var result = await CommonAddressService.instance.refresh(isLight: false);
              if (isHome) {
                var home = CommonAddressService.instance.value(AddressSetupType.home);
                if (home != null) {
                  pageViewModel.modifyEntry(EntryItemType.home, home);
                }
              } else {
                var company = CommonAddressService.instance.value(AddressSetupType.company);
                if (company != null) {
                  pageViewModel.modifyEntry(EntryItemType.company, company);
                }
              }
            }
          });
        }
      }
    }
  }

  deleteCommonAddress(CommonAddress model) async {
    T3Track.trackEventName("019919300000202");
    if (model.uuid == null) {
      return;
    }
    var result = await CommonAddressService.instance.deleteCommonAddress(model.uuid!);
    if (result) {
      EasyLoading.showToast('删除成功');
    }
    if (model.type == 0) {
      pageViewModel.deleteEntry(EntryItemType.home);
    } else {
      pageViewModel.deleteEntry(EntryItemType.company);
    }
  }

  clickFeedback() {
    //logPOISearchDebug('跳转反馈页面');
    T3POILocation? location;
    if (currentCondition != null && currentCondition?.cityName != null && currentCondition?.coordinate != null) {
      location = T3POILocation(adCode: currentCondition!.adCode ?? "", cityName: currentCondition!.cityName ?? "", coordinate: currentCondition!.coordinate!);
    } else {
      location = searchConfig.location;
    }
    POISearchSinglePointConfig config = POISearchSinglePointConfig(location: location);
    config.pageScene = PageScene.feedback;
    config.defaultText = currentCondition?.keyword;
    config.shouldCheckTableSelectedPoi = false;
    config.entryOptions = [];
    config.pointType = searchConfig.pointType;
    config.showMapSelectedFooter = false;
    config.placeholder = "请输入要搜索的地点名称";
    openSinglePointPOISearchPage(config, isPresent: false);
    if (searchConfig.isStartPoint) {
      T3Track.trackEventName('019900600001402');
    } else {
      T3Track.trackEventName('019900800002702');
    }
  }

  openFeedBack(POISearchCellViewModel? vm) {
    if (vm != null) {
      //logPOISearchDebug('反馈:${vm.poi.toJson().toString()}');
      var poi = vm.poi.toJson();
      poi['pointType'] = searchConfig.pointType.type;
      POISearchChannel.sendMsgToChannel('feedback', msgData: poi);

      T3Track.trackEventName("019918000000102", params: {"address": vm.poi.name});
    }
  }

  /// 送机场景下 当前焦点在 终点的场景
  bool isAirportLeavingAndFocusEnd(){
    if (searchConfig is POISearchMultiPointsConfig) {
      var multiConfig = searchConfig as POISearchMultiPointsConfig?;
      if (multiConfig != null) {
        // 是送机场景 并且当前选中的是 最后一个输入框 那么不能点击poi 不能选择家和公司 还有图选
        if (multiConfig.isAirportEndPoint && searchViewModel.isEndPointGetter != null) {
          var isEnd = searchViewModel.isEndPointGetter!();
          if(isEnd) {
            //logPOISearchDebug('是送机场景且点击的是终点');
            return true;
          } else {
            //logPOISearchDebug('是送机场景但点击的不是终点');
          }
        }
      }
    }
    return false;
  }
}

extension POIGen on CommonAddress {
    POIModel transformToPOI() {
      var poi = POIModel(location: location);
      poi.adCode = adCode;
      poi.name = addressTitle;
      poi.address = address;
      poi.city = city;
      poi.runtimeParams.sourceType = PointSourceType.gdSearchPOI;
      poi.runtimeParams.poiAction = (type == 1) ? PoiAction.company : PoiAction.home;
      poi.runtimeParams.sourceTrack = (type == 1) ? POISourceTrack.company : POISourceTrack.home;
      poi.cityCode = cityCode;
      return poi;
    }
}